package com.millstein.smsservice.controller;

import com.millstein.commonutils.Result;
import com.millstein.servicebase.handler.exceptionhandler.GuliException;
import com.millstein.smsservice.service.SmsService;
import com.millstein.smsservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/smsservice/sms")
@CrossOrigin
public class SmsController {

    private static final String SEND_PREFIX = "send:";
    private static final String VALID_PREFIX = "valid:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SmsService smsService;

    @GetMapping("/send/{phone}")
    public Result send(@PathVariable("phone") String phone) {

        // 1.根据手机号码查看redis中是否有验证码，有的话提示1分钟之内不能连续发送
        if (redisTemplate.hasKey(SEND_PREFIX + phone)) {
            throw new GuliException(20001, "两次验证码发送的间隔时间不能小于1分钟");
        }
        // 2.没有的话发送短信
        String code = RandomUtil.getFourBitRandom();
        Map<String, Object> params = new HashMap<>();
        params.put("verifyCode", code);
        System.out.println(code);
//        smsService.send(params, phone);
        // 3.成功后将手机号码和验证码的键值对缓存到redis中
        redisTemplate.opsForValue().set(SEND_PREFIX + phone, code, 1, TimeUnit.MINUTES); // 验证两次发送的间隔时间
        redisTemplate.opsForValue().set(VALID_PREFIX + phone, code, 5, TimeUnit.MINUTES); // 验证验证的有效时间
        return Result.ok().data("code", code);
    }
}
